﻿using System.Diagnostics;
using System.IO;
using Microsoft.Office.Interop.Excel;

namespace Haimen.Func2;

internal class YearResultMaker(
    ExcelRangeCopier interopCopier) {

  public void Make(AppEnvPath env, MonthResultInfo month) {
    //TODO: 传入月结果

    //TODO: 准备年表（dev\）
    string outPath = PrepareOut(env);
    //System.Console.WriteLine(outPath);

    //TODO: 将月结果叠加到年表对应月份sheet
    FillResult(outPath, month);
  }

  //t:HmLab.Func2.LbPrepareYearOut
  string PrepareOut(AppEnvPath path) {
    const string result = "year1_zong.xlsx";
    var ResolveTpl = () => {
      string devTpl = path.InDev(result);
      if (File.Exists(devTpl)) {
        System.Console.WriteLine($"检测到dev：{devTpl}");
        return devTpl;
      }
      string resTpl = path.ResFunc2(result);
      Debug.Assert(File.Exists(resTpl));
      return resTpl;
    };

    string outPath = path.OutDir("年汇总表.xlsx");
    string tplPath = ResolveTpl();
    File.Copy(tplPath, outPath, overwrite: true);

    return outPath;
  }

  //t:HmLab.Func2.LbFillYearResult
  void FillResult(string resultPath, MonthResultInfo monthInfo) {
    string fromPath = monthInfo.Path;
    string month = monthInfo.Month;

    Application excelApp = monthInfo.Excel;
    excelApp.ScreenUpdating = false;

    Workbooks books = excelApp.Workbooks;
    Workbook toBook = books.Open(resultPath);

    excelApp.DisplayAlerts = false;
    BookFrom[] copyArg = MakeCopyArg(fromPath, month);
    _interopCopier.Copy(toBook, copyArg);

    excelApp.ScreenUpdating = true;
    toBook.Save();
    toBook.Close();

    excelApp.Quit();
  }

  BookFrom[] MakeCopyArg(string fromPath, string month) {
    CellCopy cellArg = new(FromRange: "A1:", ToCell: "A1");
    SheetTo sheetTo = new(month, From: [new("汇总表", [cellArg])]);
    BookFrom bookFrom = new(fromPath, [sheetTo]);
    return [bookFrom];
  }

  readonly ExcelRangeCopier _interopCopier = interopCopier;
}
